package com.ruoyi.system.config;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Configuration
public class SpringConfig implements InitializingBean {
    Map<String, StringRedisTemplate> redisMap = SysRedisManegeHelper.getRedisMap();

    @Override
    public void afterPropertiesSet() throws Exception {
        try {
            Thread.sleep(1000 * 10);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Thread t = new Thread(() -> {
            while (true) {
                try {
                    // 每24h删除一次内存redisTemplate数据
                    Thread.sleep(1000 * 60 * 60 * 24);
//                    Thread.sleep(1000 * 6);
//                    System.out.println("delete");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                Set<Map.Entry<String, StringRedisTemplate>> entries = redisMap.entrySet();
                for (Map.Entry<String, StringRedisTemplate> e : entries) {
                    StringRedisTemplate redisTemplate = e.getValue();
                    LettuceConnectionFactory connectionFactory = (LettuceConnectionFactory) redisTemplate.getConnectionFactory();
                    connectionFactory.getNativeClient().shutdown(0L, 0L, TimeUnit.SECONDS);
//                    connectionFactory.destroy();
                }
                redisMap.clear();
            }
        });

        t.start();
    }
}
